
local function addToList(list, item)
	table.insert(list, item)
end
local function listGetIdx(list, item)
	local idx = 0
	for i, it in ipairs(list) do
		if it == item then
			return idx
		end
	end
	return nil
end
local function isInList(list, item)
	return listGetIdx(list, item) ~= nil
end
local function removeFromList(list, item)
	local idx = listGetIdx(list, item)
	table.remove(list, idx)
end

if (exists and not exists("AddRandomItem_Data")) or (not exists and not AddRandomItem_Data) then
	AddRandomItem_Data = {
		bricksByColor = {},
	}
	for i = 0, 63 do
		AddRandomItem_Data.bricksByColor[i] = {}
	end
end

function AddRandomItem_AddBrick(color, brick) brick = tonumber(brick); color = tonumber(color);
	local bl = AddRandomItem_Data.bricksByColor[color] or {}
	assert(not isInList(bl, brick), "Brick "..brick.." is already in color "..color)
	addToList(bl, brick)
end
function AddRandomItem_RemoveBrick(color, brick) brick = tonumber(brick); color = tonumber(color);
	local bl = AddRandomItem_Data.bricksByColor[color] or {}
	assert(isInList(bl, brick), "Brick "..brick.." is not in color "..color)
	removeFromList(bl, brick)
end

local function selectByWeight(items)
	local sum = 0
	for _, item in ipairs(items) do
		sum = sum + item.weight
	end
	
	local idx = math.random(1, sum)
	
	local sum2 = 0
	for _, item in ipairs(items) do
		sum2 = sum2 + item.weight
		if sum2 >= idx then return item end
	end
	return nil
end

function AddRandomItem_getRandomItemColorBased(color)
	color = tonumber(color)
	local bricks = AddRandomItem_Data.bricksByColor[color]
	
	local possibleItems = {}
	
	local toRemove = {}
	for brickIdx, brick in ipairs(bricks) do
		if not ts.isObject(brick) then
			table.insert(toRemove, brickIdx)
		else
			local item = ts.getobj(brick, "item")
			if ts.isObject(item) then
				local rarity = tonumber(ts.getobj(brick, "addRandomItem_rarity"))
				assert(rarity and rarity >=0 and rarity <= 9 and rarity%1 == 0, "invalid rarity on brick "..brick..": "..tostring(rarity))
				table.insert(possibleItems, {
					item = ts.callobj(item, "getDatablock"),
					weight = 10-rarity,
				})
			end
		end
	end
	for i = #toRemove, 1, -1 do table.remove(bricks, toRemove[i]) end
	
	local item = selectByWeight(possibleItems)
	if item then
		return item.item
	end
end
